import 'dart:io';


import 'package:flutter/material.dart';
import "package:get/get.dart";
import 'package:osg/controllers/http.dart';
import 'package:http/http.dart' as http;
import '../../middleware/h5_upimg.dart' if (dart.library.io) '../../middleware/andino_upimg.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
import 'package:path/path.dart' as path;



RxList imgList = [].obs;
late TextEditingController  _controller;


class Identification extends StatefulWidget {
  @override
  _ImageUploadScreenState createState() => _ImageUploadScreenState();
}

class _ImageUploadScreenState extends State<Identification> {
  final RxInt _selectedValue = 1.obs;
   final type =  Get.parameters['type'];//1个人


Future<void> downloadAndOpenFile(String url) async {
  // 请求存储权限（Android）
  if (Platform.isAndroid) {
    final status = await Permission.storage.request();
    if (status.isDenied) {
      // 权限被拒绝
      return;
    }
  }

  // 获取存储目录
  Directory? directory;
  try {
    if (Platform.isAndroid) {
      directory = await getExternalStorageDirectory();
    } else {
      directory = await getApplicationDocumentsDirectory();
    }
    if (directory == null) {
      throw Exception('无法获取存储目录');
    }

    // 创建下载目录（如果不存在）
    final downloadDirectory = Directory('${directory.path}/downloads');
    if (!downloadDirectory.existsSync()) {
      await downloadDirectory.create(recursive: true);
    }

    // 下载文件
    final response = await http.get(Uri.parse(url));
    if (response.statusCode != 200) {
      throw Exception('下载失败，状态码: ${response.statusCode}');
    }

    // 生成文件名（从URL中提取或自定义）
    final filename = url.split('/').last;
    final file = File('${downloadDirectory.path}/$filename');

    // 写入文件
    await file.writeAsBytes(response.bodyBytes);

    const types = {".doc":"application/msword"};
    final extension  = path.extension(file.path);
    OpenFile.open(file.path, type: types[extension]);

  } catch (e) {
    print('下载或打开文件出错: $e');
    // 可以在这里显示错误提示
  }
}






  // gerenshenfen

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Stack(
          children: [
            Container(
              child: Image.asset(
                type=='1'?'static/images/gerenshenfen.png':'static/images/guangfang.png',
                fit: BoxFit.fitWidth,
              ),
            ),
            Positioned(
              left: 8.0,
              top: 20,
              child: IconButton(
                onPressed: () {
                  Get.back();
                  print('object');
                },
                icon: Image.asset(
                  'static/images/back.png',
                  width: 22,
                  fit: BoxFit.fitWidth,
                ),
              ),
            ),
          ],
        ),
        Container(
          height: 20,
          transform: Matrix4.translationValues(0.0, -10.0, 0.0),
          decoration: BoxDecoration(
              color: Color(0xffffffff),
              borderRadius: BorderRadius.circular(20)),
        ),
        Container(
          transform: Matrix4.translationValues(0.0, -10.0, 0.0),
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '认证称号',
                style: TextStyle(fontSize: 14),
              ),
              InputFieldWithCounter(),
              SizedBox(height: 20),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '附件',
                    style: TextStyle(fontSize: 14),
                  ),
                  GestureDetector(
                    onTap: (){
                      if(type=='1'){
                      downloadAndOpenFile('http://osg4.wexiang.vip/geren.doc');

                      }else{
                      downloadAndOpenFile('http://osg4.wexiang.vip/guangfang.doc');

                      }
                    },
                    child:  Row(
                    children: [
                      Image.asset(
                        'static/web/haixiazai.png',
                        width:35,
                        fit: BoxFit.fitWidth,
                      ),
                      Text(
                        ' 附件模板',
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  )
                    ,
                  )
                 
                ],
              ),
              Obx(
                () => Wrap(
                  spacing: 10,
                  runSpacing: 10,
                  children: [
                    for (int i = 0; i < imgList.length; i++)
                      Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(10), // 设置圆角半径
                            child: Image.network(
                              imgList[i],
                              width: 80,
                              height: 80,
                              fit: BoxFit.fill,
                            ),
                          ),
                          Positioned(
                            top: 5.0,
                            right: 5,
                            child: GestureDetector(
                              onTap: () {
                                imgList.removeAt(i);
                              },
                              child: ClipRRect(
                                borderRadius:
                                    BorderRadius.circular(20), // 设置圆角半径
                                child: Image.asset(
                                  width: 20,
                                  height: 20,
                                  'static/guanbi.png',
                                  fit: BoxFit.fill,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: Color(0xfff5f5f5)),
                      child: IconButton(
                        iconSize: 30,
                        icon: Icon(Icons.add),
                        color: Color(0xff999999),
                        onPressed: () async {
                          // 点击事件处理

                          final result = await ImageUploader.uploadImage();
                          Get.back();
                          if (result != null&&result !='') {
                            Get.back();
                            imgList.add(result);
                          }
                        },
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),

        Expanded(child: Container()), // 用于推到底部
        Align(
            alignment: Alignment.center,
            child: Column(
              children: [
                // Container(
                //   alignment: Alignment.topLeft,
                //   padding: EdgeInsets.symmetric(horizontal: 15),
                //   child: Text(
                //     '拒绝理由：',
                //     style: TextStyle(color: Color(0xffef0000), fontSize: 12),
                //   ),
                // ),
                // Container(
                //   alignment: Alignment.topLeft,
                //   padding: EdgeInsets.symmetric(horizontal: 15),
                //   child: Text(
                //     '需要补充公司（机构、单位）工作证明（备注认证信息）并加盖公章；',
                //     style: TextStyle(color: Color(0xffef0000), fontSize: 12),
                //   ),
                // ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Transform.scale(
                      scale: 0.8,
                      child: Obx(() => Radio<int>(
                            value: 1,
                            groupValue: _selectedValue.value,
                            onChanged: (value) {
                              print('object');
                              _selectedValue.value = value!;
                            },
                          )),
                    ),
                    Text(
                      '已阅读并同意',
                      style: TextStyle(fontSize: 12),
                    ),
                    GestureDetector(
                      onTap: (){
                         Get.toNamed('/agreement?type=1', arguments: {'type': '1'});
                      },
                      child: Text(
                      '《用户协议》',
                      style: TextStyle(color: Color(0xff0A72D9), fontSize: 12),
                    ),
                    )
                    ,
                  ],
                ),
                GestureDetector(
                  onTap: () => {
                    if(_controller.text.isNotEmpty){
                         if(imgList.isNotEmpty){
                            Get.find<HTTPS>().postData('/bbs/identity', {
                              'title':_controller.text,
                              'type':type,
                              'images':imgList.join(','),
                            }).then((res){
                              if(res!=null){
                                Get.toNamed('/examine?type=1');
                              }
                            })
                         }else{
                          Get.find<HTTPS>().showTost('请上传图片')
                        }
                    }else{
                      Get.find<HTTPS>().showTost('请输入')
                    }


                    
                  },
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular((40)),
                      gradient: LinearGradient(
                        colors: [
                          Color(0xff2189E7),
                          Color(0xffBF67F8),
                        ], // 定义颜色列表
                        begin: Alignment.topLeft, // 渐变开始的位置
                        end: Alignment.bottomRight, // 渐变结束的位置
                      ),
                    ),
                    width: 280,
                    height: 40,
                    child: Text('提交',
                        style:
                            TextStyle(fontSize: 16, color: Color(0xffffffff))),
                  ),
                ),
              ],
            )),
        SizedBox(height: 15)
      ],
    ));
  }
}

class InputFieldWithCounter extends StatefulWidget {
  @override
  _InputFieldWithCounterState createState() => _InputFieldWithCounterState();
}

class _InputFieldWithCounterState extends State<InputFieldWithCounter> {
  RxInt currentCount = 0.obs; // 当前计数器值（虽然在这个示例中不会改变）

  @override
  void initState() {
    super.initState();
    _controller =  TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(top: 10),
        decoration: BoxDecoration(
            border: Border(bottom: BorderSide(color: Color(0xffdddddd)))),
        child: Row(
          children: [
            Expanded(
              child: TextField(
                onChanged: (value) {
                  currentCount.value = value.length;
                },
                maxLength: 20,
                controller: _controller,
                decoration: InputDecoration(
                  counterText: '',
                  hintStyle: TextStyle(color: Color(0xff999999), fontSize: 12),
                  border: InputBorder.none, // 移除边框
                  hintText: '请填写认证称号',
                ),
              ),
            ),
            SizedBox(width: 8),
            Obx(() => Text(
                  '${currentCount}/20',
                  style: TextStyle(color: Colors.grey),
                )),
          ],
        ));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
